const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

const db = cloud.database()

exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  const { action, data } = event
  
  console.log('消息管理云函数调用:', { action, openid: wxContext.OPENID })
  
  try {
    switch (action) {
      case 'sendOrderNotification':
        return await sendOrderNotification(wxContext, data)
      case 'sendProjectUpdate':
        return await sendProjectUpdate(wxContext, data)
      case 'sendSystemMessage':
        return await sendSystemMessage(wxContext, data)
      case 'getNotifications':
        return await getNotifications(wxContext, data)
      case 'markAsRead':
        return await markAsRead(wxContext, data)
      default:
        return {
          success: false,
          error: '未知的操作类型'
        }
    }
  } catch (error) {
    console.error('消息管理云函数错误:', error)
    return {
      success: false,
      error: error.message
    }
  }
}

// 发送订单通知
async function sendOrderNotification(wxContext, data) {
  const { orderId, type, content } = data
  const openid = wxContext.OPENID
  
  try {
    // 创建通知记录
    const notification = {
      openid: openid,
      type: 'order',
      title: getOrderNotificationTitle(type),
      content: content,
      orderId: orderId,
      isRead: false,
      createTime: new Date(),
      priority: type === 'urgent' ? 'high' : 'normal'
    }
    
    await db.collection('notifications').add({
      data: notification
    })
    
    // 这里可以调用微信模板消息API
    // await sendWeChatTemplateMessage(openid, notification)
    
    return {
      success: true,
      message: '通知发送成功'
    }
  } catch (error) {
    console.error('发送订单通知失败:', error)
    throw error
  }
}

// 发送项目更新通知
async function sendProjectUpdate(wxContext, data) {
  const { projectId, milestone, progress } = data
  const openid = wxContext.OPENID
  
  try {
    const notification = {
      openid: openid,
      type: 'project',
      title: '项目进度更新',
      content: `项目里程碑"${milestone}"已完成，当前进度：${progress}%`,
      projectId: projectId,
      isRead: false,
      createTime: new Date(),
      priority: 'normal'
    }
    
    await db.collection('notifications').add({
      data: notification
    })
    
    return {
      success: true,
      message: '项目更新通知发送成功'
    }
  } catch (error) {
    console.error('发送项目更新通知失败:', error)
    throw error
  }
}

// 发送系统消息
async function sendSystemMessage(wxContext, data) {
  const { title, content, type = 'info' } = data
  const openid = wxContext.OPENID
  
  try {
    const notification = {
      openid: openid,
      type: 'system',
      title: title,
      content: content,
      isRead: false,
      createTime: new Date(),
      priority: type === 'urgent' ? 'high' : 'normal'
    }
    
    await db.collection('notifications').add({
      data: notification
    })
    
    return {
      success: true,
      message: '系统消息发送成功'
    }
  } catch (error) {
    console.error('发送系统消息失败:', error)
    throw error
  }
}

// 获取通知列表
async function getNotifications(wxContext, params) {
  const openid = wxContext.OPENID
  const { limit = 20, skip = 0, unreadOnly = false } = params || {}
  
  try {
    let query = db.collection('notifications').where({
      openid: openid
    })
    
    if (unreadOnly) {
      query = query.where({
        isRead: false
      })
    }
    
    const result = await query
      .orderBy('createTime', 'desc')
      .limit(limit)
      .skip(skip)
      .get()
    
    // 统计未读数量
    const unreadResult = await db.collection('notifications')
      .where({
        openid: openid,
        isRead: false
      })
      .count()
    
    return {
      success: true,
      data: result.data,
      unreadCount: unreadResult.total,
      total: result.data.length
    }
  } catch (error) {
    console.error('获取通知列表失败:', error)
    throw error
  }
}

// 标记为已读
async function markAsRead(wxContext, params) {
  const { notificationIds } = params
  const openid = wxContext.OPENID
  
  try {
    if (Array.isArray(notificationIds)) {
      // 批量标记已读
      const promises = notificationIds.map(id => 
        db.collection('notifications')
          .where({
            _id: id,
            openid: openid
          })
          .update({
            data: {
              isRead: true,
              readTime: new Date()
            }
          })
      )
      
      await Promise.all(promises)
    } else {
      // 单个标记已读
      await db.collection('notifications')
        .where({
          _id: notificationIds,
          openid: openid
        })
        .update({
          data: {
            isRead: true,
            readTime: new Date()
          }
        })
    }
    
    return {
      success: true,
      message: '标记已读成功'
    }
  } catch (error) {
    console.error('标记已读失败:', error)
    throw error
  }
}

// 获取订单通知标题
function getOrderNotificationTitle(type) {
  const titleMap = {
    'created': '订单创建成功',
    'confirmed': '订单已确认',
    'surveying': '现场查勘中',
    'designing': '方案设计中',
    'quoted': '报价已完成',
    'in_progress': '项目实施中',
    'testing': '质量验收中',
    'completed': '订单已完成',
    'cancelled': '订单已取消',
    'urgent': '紧急订单通知'
  }
  
  return titleMap[type] || '订单状态更新'
}

// 发送微信模板消息（示例，需要配置模板ID）
async function sendWeChatTemplateMessage(openid, notification) {
  try {
    // 这里需要配置微信模板消息
    // const result = await cloud.openapi.templateMessage.send({
    //   touser: openid,
    //   template_id: 'YOUR_TEMPLATE_ID',
    //   data: {
    //     title: {
    //       value: notification.title
    //     },
    //     content: {
    //       value: notification.content
    //     },
    //     time: {
    //       value: new Date().toLocaleString()
    //     }
    //   }
    // })
    
    console.log('模板消息发送功能需要配置模板ID')
    return { success: true }
  } catch (error) {
    console.error('发送模板消息失败:', error)
    return { success: false, error: error.message }
  }
} 